/**
 * 
 */
package cn.ivicar.app.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.DeviceParamDetail;
import cn.com.carsmart.ws.model.DeviceSetting;
import cn.com.carsmart.ws.model.ParamDefinition;
import cn.com.carsmart.ws.service.DeviceParamDetailManager;
import cn.com.carsmart.ws.service.DeviceSettingManager;
import cn.com.carsmart.ws.service.ParamDefinitionManager;
import cn.ivicar.app.controller.util.DeviceParamEnum;
import cn.ivicar.redis.JedisClusterFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.JedisCluster;

/**
 * @author liurunbin 2017年6月22日 cn.ivicar.app.controller
 */
public class DevicesSettingController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(DevicesSettingController.class);

	@Inject
    private ParamDefinitionManager paramDefinitionManager;
	@Inject
	private DeviceSettingManager deviceSettingManager;
	@Inject
	private DeviceParamDetailManager deviceParamDetailManager;

	private static String REDIS_PREFIX = "ivicar:device:setting";

	public JSONObject getChangeId() throws CarsmartException {
		long changeId = 0;
		BaseExample example = deviceSettingManager.getExample();
		example.setOrderByClause("updated desc");
		example.setLimitStart(0);
		example.setLimitCount(1);
		List<DeviceSetting> list = deviceSettingManager.listByBaseExample(example);
		if (list != null && !list.isEmpty() && list.get(0).getUpdated() != null) {
			changeId = list.get(0).getUpdated().getTime();
		}
		
		BaseExample example2 = paramDefinitionManager.getExample();
        example2.setOrderByClause("updated desc");
        example2.setLimitStart(0);
        example2.setLimitCount(1);
        List<ParamDefinition> list2 = paramDefinitionManager.listByBaseExample(example2);
        if (list2 != null && !list2.isEmpty() && list2.get(0).getUpdated() != null) {
            long updated = list2.get(0).getUpdated().getTime();
            changeId = changeId > updated ? changeId : updated;
        }
        
		JSONObject result = new JSONObject();
		result.put("changeId", changeId);

		try {
			JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
			String value = cluster.get(REDIS_PREFIX + "changeId");
			if (StringUtils.isBlank(value)) {
				cluster.set("changeId", changeId + "");
			} else if (Long.valueOf(value) < changeId) {
				cluster.set("changeId", changeId + "");
				//cluster.del(REDIS_PREFIX);
			}
		} catch (Exception e) {
			LOGGER.error("请求最新的设备设置的chargeId出错");
			e.printStackTrace();
		}
		return result;
	}

	public JSONObject getSettings() throws CarsmartException {
		/*JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
		String str = cluster.get(REDIS_PREFIX);
		if (StringUtils.isNotBlank(str)) {
			return JSONObject.fromObject(str);
		}*/
		JSONArray array = new JSONArray();

		List<DeviceParamDetail> deviceParams = deviceParamDetailManager.list();
		if (deviceParams == null || deviceParams.isEmpty()) {
			return new JSONObject();
		}

		Map<Integer, Object> simpleParamDefine = new HashMap<Integer, Object>();

		JSONObject paramDefine = new JSONObject();
		JSONArray camera_num = new JSONArray();
		camera_num.add(new JSONObject().accumulate("name", "四路摄像头").accumulate("value", "4"));
		camera_num.add(new JSONObject().accumulate("name", "六路摄像头").accumulate("value", "6"));
		paramDefine.put("camera_num", camera_num);

		for (DeviceParamDetail detail : deviceParams) {
		    JSONObject item = new JSONObject();
            item.put("name", detail.getName());
            item.put("value", detail.getValue());
			String key = DeviceParamEnum.get(detail.getDeviceParamId().intValue()).getValue();
			Object object = paramDefine.get(key);
			JSONArray items = null;
			if (object == null) {
				items = new JSONArray();
	            items.add(item);
				paramDefine.put(key, items);
			}else{
				items = paramDefine.getJSONArray(key);
				items.add(item);
			}
			
			simpleParamDefine.put(detail.getParamDefinitionId(), detail.getValue());
		}

		List<DeviceSetting> list = deviceSettingManager.list();
		if (list != null && !list.isEmpty()) {
			for (DeviceSetting setting : list) {
				array.add(DeviceSettingToJSON(setting, simpleParamDefine));
			}
		}
		JSONObject data = new JSONObject();
		data.put("settings", array);
		data.putAll(paramDefine);

		JSONObject result = new JSONObject();
		result.put("data", data);

		//cluster.setex(REDIS_PREFIX, 24 * 60 * 60, result.toString());

		return result;
	}

	private JSONObject DeviceSettingToJSON(DeviceSetting setting, Map<Integer, Object> simpleParamDefine) {
		JSONObject object = new JSONObject();
		object.put("can_type", setting.getDecodeType() == null ? "" : simpleParamDefine.get(setting.getDecodeType()));
		object.put("skin", setting.getInterfaced() == null ? "" : simpleParamDefine.get(setting.getInterfaced()));
		object.put("front_back", setting.getFbView() == null ? "" : simpleParamDefine.get(setting.getFbView()));
		object.put("left_right", setting.getTurnView() == null ? "" : simpleParamDefine.get(setting.getTurnView()));
		object.put("trace_type", setting.getTrackType() == null ? "" : simpleParamDefine.get(setting.getTrackType()));

		object.put("camera_num", setting.getCameraCount() == null ? "" : setting.getCameraCount() + "");
		object.put("trace_ratio", setting.getTrackCoefficient() == null ? "" : setting.getTrackCoefficient() + "");
		object.put("trace_wheel_base", setting.getWheelBase() == null ? "" : setting.getWheelBase() + "");
		object.put("trace_tread", setting.getWheelTrack() == null ? "" : setting.getWheelTrack() + "");
		object.put("trace_before", setting.getFrontWheelDist() == null ? "" : setting.getFrontWheelDist() + "");
		object.put("fb_param", setting.getScreenParam() == null ? "" : setting.getScreenParam());
		return object;
	}

	public boolean clearRedis() throws CarsmartException {
		boolean result = true;
		try {
			JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
			cluster.del(REDIS_PREFIX + "changeId");
			cluster.del(REDIS_PREFIX);
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}

}
